<?php

namespace app\admin\service;

use app\common\Error;
use app\model\PayRecord;
use app\common\Common;

class PayComplaintService
{
    private $payRecordModel;

    public function __construct(PayRecord $payRecordModel)
    {
        $this->payRecordModel = $payRecordModel;
    }

    // 获取投诉列表
    public function getComplaintList($params)
    {
        $body = ['complainted_mchid' => config('enum.wechat_third_party_applet_payment')['mch_id']];
        $body['limit'] = $params['limit'] ?? 10;
        $page = $params['page'] ?? 1;
        $body['offset'] = ($page - 1) * 10;

        if (!empty($params['begin_date'])) {
            $body['begin_date'] = $params['begin_date'];
        } else {
            $body['begin_date'] = date('Y-m-d', time() - 30 * 86400);
        }

        if (!empty($params['end_date'])) {
            $body['end_date'] = $params['end_date'];
        } else {
            $body['end_date'] = date('Y-m-d');
        }

        if (!empty($params['begin_date']) && !empty($params['end_date'])) {
            if ( (strtotime($params['end_date']) - strtotime($params['begin_date'])) / 86400 > 30) {
                return ['message' => Error::QUERY_DATE_SPAN_NOT_EXCEED_30_DAY];
            }
        }

        $url = 'https://wx.palmpay.cn/v3/complaint/queryList';
        $requestUrl = $url . '?' . http_build_query($body);

        $result = file_get_contents($requestUrl);

        $result = json_decode($result, true);
        if ($result['code'] != 0) {
            return ['message' => $result['message']];
        }

        $data = $result['data'];

        $orderNo = [];
        if ($data['data']) {
            foreach ($data['data'] as $key => $value) {
                $time = explode('+', $result['data']['data'][$key]['complaint_time']);
                $data['data'][$key]['complaint_time'] = str_replace('T', ' ', $time[0]);

                $data['data'][$key]['amount'] = round($value['complaint_order_info'][0]['amount'] / 100, 2);
                $data['data'][$key]['wechat_order_no'] = $value['complaint_order_info'][0]['transaction_id'];

                $orderNo[] = $value['complaint_order_info'][0]['transaction_id'];
                unset($data['data'][$key]['complaint_order_info']);
            }

            $orderInfo = $this->payRecordModel->getInfo(['wechat_order_no' => $orderNo], 'wechat_order_no, order_no, uid');
            $order = [];
            foreach ($orderInfo as $key => $value) {
                $order[$value['wechat_order_no']] = $value;
            }

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['uid'] = empty($order[$value['wechat_order_no']]) ? '' : $order[$value['wechat_order_no']]['uid'];
                $data['data'][$key]['order_no'] = empty($order[$value['wechat_order_no']]) ? '' : $order[$value['wechat_order_no']]['order_no'];
            }
        }

        $data['page'] = $page;
        $data['total'] = $data['total_count'];

        return $data;
    }

    // 回复用户
    public function replyUser($params)
    {
        $body = [
            'complaint_id' => $params['complaint_id'],
            'complainted_mchid' => config('enum.wechat_third_party_applet_payment')['mch_id'],
            'response_content' => $params['response_content']
        ];

        $url = 'https://wx.palmpay.cn/v3/complaint/responseUser';

        $result = Common::curlRequest($url, 'POST', json_encode($body), ['Content-Type: application/json']);

        $data = json_decode($result, true);

        if ($data['code']) {
            return ['message' => $data['message']];
        }

        return [];
    }

    // 反馈处理完成
    public function complete($params)
    {
        $body = [
            'complaint_id' => $params['complaint_id'],
            'complainted_mchid' => config('enum.wechat_third_party_applet_payment')['mch_id']
        ];

        $url = 'https://wx.palmpay.cn/v3/complaint/complete';

        $result = Common::curlRequest($url, 'POST', json_encode($body), ['Content-Type: application/json']);

        $data = json_decode($result, true);

        if ($data['code']) {
            return ['message' => $data['message']];
        }

        return [];
    }

    // 更新退款状态
    public function updateRefundStatus($params)
    {
        $body = [
            'complaint_id' => $params['complaint_id'],
            'action' => $params['action'],
            'launch_refund_day' => 0
        ];

        $url = 'https://wx.palmpay.cn/v3/complaint/updateRefund';

        $result = Common::curlRequest($url, 'POST', json_encode($body), ['Content-Type: application/json']);

        $result = json_decode($result, true);

        if ($result['code'] != 0) {
            return ['message' => $result['message']];
        }

        if (!empty($result['data'])) {
            $data = json_decode($result['data'], true);
            if (!empty($data['message'])) {
                return ['message' => $data['message']];
            }
        }

        return [];
    }

    // 退款
    public function refund($params)
    {
        $orderNo = $params['order_no'];
        $info = $this->payRecordModel->getDataByWhere(['order_no' => $orderNo], 'platform_order_no, total_fee');
        $pdorderid = $info['platform_order_no'];

        // $money = $params['return_money'];

        $wechatPayConfig = config('enum.wechat_third_party_applet_payment');
        $mchId = $wechatPayConfig['mch_id'];
        $appid = $wechatPayConfig['appid'];
        $appkey = $wechatPayConfig['appkey'];
        $service = $wechatPayConfig['service'];

        $outRefundNo = date('YmdHis') . rand(1000, 10000);
        $money = intval($info['total_fee'] * 100);
        $version = '3.0';
        $returnMoney = intval($params['return_money'] * 100);

        $body = [
            'appid' => $appid,
            'mchId' => $mchId,
            'pdorderid' => $pdorderid,
            'money' => $money,
            'version' => $version,
            'outRefundNo' => $outRefundNo,
            'refundMoney' => $returnMoney,
            'refundReason' => $params['refund_reason'],
            'sign' => md5($mchId.$appid.$pdorderid.$money.$version.$outRefundNo.$returnMoney.$appkey)
        ];

        $url = 'https://pay.palmpay.cn/sdkServer/thirdpays/refund';

        $requestUrl = $url . '?' . http_build_query($body);

        $result = file_get_contents($requestUrl);

        $result = json_decode($result, true);

        if ($result['resultCode'] != 0) {
            return ['message' => $result['message']];
        }

        return [];
    }
}